import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

/**
 * 下推状态：工单下推、返厂下推
 */
export const usePushDown = defineStore('pushDown', () => {
  // 下推类型
  const pushDownType = ref<
    'orderToReturnFactory' | 'returnFactoryToOrder' | 'saleOutboundPushDownToOrder' | ''
  >('')

  // 工单商品（内部使用）
  const _orderGood = ref<(OrderDetailAPIResponse.GoodListItem & { isStandby: number }) | null>(null)

  // 工单详情（内部使用）
  const _orderDetail = ref<OrderDetail | null>(null)

  // 返厂商品（内部使用）
  const _returnFactoryGood = ref<ReturnFactoryDetailGood | null>(null)

  // 返厂详情（内部使用）
  const _returnFactoryDetail = ref<ReturnFactoryDetail | null>(null)

  // 工单商品（外部使用）
  const orderGood = computed(() => {
    return _orderGood.value
  })

  // 工单详情（外部使用）
  const orderDetail = computed(() => {
    return _orderDetail.value
  })

  // 返厂商品（外部使用）
  const returnFactoryGood = computed(() => {
    return _returnFactoryGood.value
  })

  // 返厂详情（外部使用）
  const returnFactoryDetail = computed(() => {
    return _returnFactoryDetail.value
  })

  /**
   * 清除下推信息
   */
  const clearPushDownInfo = () => {
    pushDownType.value = ''
    _orderGood.value = null
    _orderDetail.value = null
    _returnFactoryGood.value = null
  }

  /**
   * 设置工单下推信息
   * @param good - 工单商品
   */
  const setOrderPushDownInfo = (
    good: OrderDetailAPIResponse.GoodListItem & { isStandby: number },
    detail: OrderDetail,
  ) => {
    pushDownType.value = 'orderToReturnFactory'
    _orderGood.value = good
    _orderDetail.value = detail
  }

  /**
   * 设置返厂下推信息
   * @param good - 返厂商品
   */
  const setReturnFactoryPushDownInfo = (
    good: ReturnFactoryDetailGood,
    detail: ReturnFactoryDetail,
  ) => {
    pushDownType.value = 'returnFactoryToOrder'
    _returnFactoryGood.value = good
    _returnFactoryDetail.value = detail
  }

  /**
   * 设置工单下推信息
   * @param good - 工单商品
   */
  const setSaleOutboundPushDownInfo = (
    good: OrderDetailAPIResponse.GoodListItem & { isStandby: number },
    detail: OrderDetail,
  ) => {
    pushDownType.value = 'saleOutboundPushDownToOrder'
    _orderGood.value = good
    _orderDetail.value = detail
  }

  return {
    orderGood,
    orderDetail,
    pushDownType,
    returnFactoryGood,
    returnFactoryDetail,
    clearPushDownInfo,
    setOrderPushDownInfo,
    setSaleOutboundPushDownInfo,
    setReturnFactoryPushDownInfo,
  }
})
